/**
 * 
 */
package controlleur.form;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import annuaire.beans.Promotion;
import annuaire.rmi.remotedObject.IRemotedAnnuaire;
import annuaire.rmi.remotedObject.IRemotedUser;
import form.bean.PromotionForm;

/**
 * Contrôleur responsable du traitement du formulaire de création d'une
 * promotion par l'administrateur
 * 
 * @author Yannick Lorenzati & Stephanie Malakian
 * 
 */
public class AddPromoFormControlleur extends SimpleFormController {

	/**
	 * Reference vers l'objet distant Annuaire
	 */
	private IRemotedAnnuaire remotedAnnuaire;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax
	 * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object commandAjout,
			BindException errors) throws Exception {

		PromotionForm pForm = (PromotionForm) commandAjout;

		Promotion p = new Promotion();
		p.setPromoYear(pForm.getPromoYear());
		p.setTitle(pForm.getTitle());
		p.setDescription(pForm.getDescription());

		// Recuperation de l'utilisateur en session
		IRemotedUser user = (IRemotedUser) request.getSession().getAttribute(
				"user");
		user.getAdminService().addPromo(p);

		// On reste sur la meme page pour l'ajout
		ModelAndView mav = showForm(request, response, errors);
		mav.addObject("successAddPromo", "Promotion ajoutée avec succes");
		return mav;
		// return new ModelAndView("redirect", "model", myModel) ;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject
	 * (javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws ServletException {

		return new PromotionForm();
	}

	/**
	 * @param remotedAnnuaire
	 */
	public void setRemotedAnnuaire(IRemotedAnnuaire remotedAnnuaire) {
		this.remotedAnnuaire = remotedAnnuaire;
	}

	/**
	 * @return
	 */
	public IRemotedAnnuaire getRemotedAnnuaire() {
		return remotedAnnuaire;
	}
}
